<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/18
 * Time: 21:44
 */

namespace app\home\controller;


use think\Controller;
use think\db\Connection;
use  think\Db;
use think\facade\Cache;

class Index extends  Common
{

    public $sensor = [
        'qiya' => '气压',
        'wendu' => '温度',
        'shidu' => '湿度',
        'co2' => '二氧化碳',
        'guangzhao' => '光照',
        'pm2' => 'PM2.5',
        'pm1' => 'PM1',
        'pm10' => 'PM10',
        'fengsu' => '风速',
        'fengxiang' => '风向',
        'zaoyin' => '噪音',
        'tushidu' => '土湿度',
        'tuwendu' => '土温度',
        'diandao' => '电导',
        'yanfen' => '养分'
    ];

    // index 首页
    public  function index()
    {
        return $this->fetch();
    }

    //  实时页面
    public function real_time()
    {
        $data = Cache::remember('sensor_info', function () {
            $sql2 = " SELECT * from  (SELECT
            a.*, b.sensor_name,
            b.id AS sensor_id,
            c.`range`,
        c.img
        FROM
            nyd_data a
        INNER JOIN nyd_sensor b ON a.dev_id = b.id
        INNER JOIN nyd_sensor_type c ON b.type_id = c.id
        WHERE
            b.is_del = 1
        AND b.is_bad = 1
        AND b.is_open = 1    
        ORDER BY a.now_time DESC) b
        
        GROUP BY  b.sensor_id  ";
            $data = Db::name("nyd_data")->query($sql2);

            foreach ($data as $key => $value) {
                $data[$key]['sensor_cn_name'] = $this->sensor[$value['sensor_name']];
            }
            return $data;
        }, 120);

        if (request()->isPost()) {

            // 更新实时数据
            $now_data = Cache::store('redis')->get('wenshi_15');

            $now_data = json_decode($now_data, true);
            foreach ($now_data['data'] as $key => $value) {
                $sensor_data[$value['mac_id']] = $value['data'];
            }
            return $sensor_data;
        }

        // 实时数据
        $now_data = Cache::store('redis')->get('wenshi_15');

        $now_data = json_decode($now_data, true);
        foreach ($now_data['data'] as $key => $value) {
            $sensor_data[$value['mac_id']] = $value['data'];
        }

        $this->assign('info', $data);
        $this->assign('sensor_data', $sensor_data);

        return $this->fetch();
    }

    // 历史数据
    public function history()
    {
        // 读缓存
        if (request()->isPost()) {
            $day = input('post.select');
            $time_data = Cache::store('redis')->get('nyd_data_' . $day);
            $time_data = json_decode($time_data, true);
            if (!$time_data) {

                // 宝塔设有定时任务 自动获取昨天数据 
                //现在取不到就没有代表没有昨天数据 取假数据

                $option = $this->jiadata();
            } else {
                $option = $time_data;
            }
            return ['opt' => $option];
        }

        $yes_day = date('Y-m-d', time() - 86400);
        $time_data = Cache::store('redis')->get('nyd_data_' . $yes_day);
        $time_data = json_decode($time_data, true);
        if (!$time_data) {
            $option = $this->jiadata();
        } else {
            $option = $time_data;
        }
        $this->assign('opt', json_encode($option));

        return $this->fetch();
    }

    //综合展示历史页面
    public function show_history(){
        if (request()->isPost()) {
            $day = input('post.select');
            $time_data = Cache::store('redis')->get('nyd_data_' . $day);
            $time_data = json_decode($time_data, true);
            if (!$time_data) {

                // 宝塔设有定时任务 自动获取昨天数据
                //现在取不到就没有代表没有昨天数据 取假数据

                $option = $this->jiadata();
            } else {
                $option = $time_data;
            }
            return ['opt' => $option];
        }

        $yes_day = date('Y-m-d', time() - 86400);
        $time_data = Cache::store('redis')->get('nyd_data_' . $yes_day);
        $time_data = json_decode($time_data, true);
        if (!$time_data) {
            $option = $this->jiadata();
        } else {
            $option = $time_data;
        }
        $this->assign('opt', json_encode($option));

        return $this->fetch();
    }

    // 控制页面
    public function control()
    {         
        if (isset($_POST['value'])) {
            $data = $_POST;
            $sql = " update nyd_control_dev set is_open =" . $data['value'] . "   where id = " . $data['id'];
            $row = Db::name("nyd_control_dev")->execute($sql);
            if ($row) {
                $res['code'] = 1;
            } else {
                $res['code'] = 0;
            }
            return $res;
        } else {
            $sql = "SELECT a.id,b.gateway_id,a.gateway_id as wangguan_id,a.is_open,a.is_bad,a.control_shortname,a.control_id,a.open_imgUrl,a.close_imgUrl  from  nyd_control_dev  as a inner join  nyd_gateway as b on a.gateway_id = b.id and   a.is_del =1 ";
            $result = Db::name("nyd_control_dev")->query($sql);
            $this->assign("result", $result);
            $this->assign("count", count($result));
            return $this->fetch();
        }

    }

	// 控制页面每秒获取状态数据
	   public function get_status()
    {
		// 获取redis数据
        $status_data = \cache("devwenshi_15");
		$kv['key'] = array_keys($status_data);
		$kv['value'] = array_values($status_data);
		return $kv;
    }
	
	// 摄像头页面
	public function showData(){
		return $this->fetch('show');
	}
	
	
    // 接收到的数据
    public function data()
    {
        // 展示拿到的最后一条数据
        $res = Cache::store('redis')->get('wenshi_12');
        // print($res);
        $res = json_decode($res, true);
		
        foreach ($res['data'] as $key => $value) {
            $res['data'][$key]['sensor_name'] = $this->sensor[$value['mac_id']];
        }

        if (request()->isPost()) {

            // 更新展示拿到的最后一条数据
            $res = Cache::store('redis')->get('wenshi_12');
            $res = json_decode($res, true);
            foreach ($res['data'] as $key => $value) {
                $sensor_data[$value['mac_id']] = $value['data'];
            }
            return $sensor_data;
        }
        $this->assign("data", $res);
        return $this->fetch();
    }

    /**
     * 获取联动控制关系
     *
     * @return control_relation
     */
    public function getControlRelation()
    {
        $control_id = input('post.control_id');
        $wangguan_id = input('post.wangguan_id');
        $control_relation = Db::name('nyd_control_dev')->where('control_id', $control_id)->where("gateway_id",$wangguan_id)->value('control_relation');
        if ($control_relation) {
            $control_relation = explode(',', $control_relation);
            return ['code' => 1, 'data' => $control_relation];
        } else {
            return ['code' => 0];
        }
    }

    /**
     * 从数据库查找昨天传感器数据
     *
     * @return void
     */
    public function gettubiaodata()
    {
        $sql = "SELECT CONCAT(b.gateway_id,',',a.id)  as id,a.sensor_name from nyd_sensor a inner join nyd_gateway  b on a.gateway_id=b.id";
        $data = Db::query($sql);

        // x轴
        $x_title = ['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'];
        $time_line = $opt =  $text = [];

        $legend['x'] = ['right'];
        $legend['data'] = [];
        $legend['selected'] = [];
        $dddd = [];
        $yesterday = date('Y-m-d', (time() - 86400));
        foreach ($data as $key => $value) {
            $param = $value['id'];
            // 拼接存储过程参数
            list($gateway, $dev_id) = explode(',', $param);
            $way = $gateway;
            $gateway = "'$gateway'";
            $param = $gateway . ',' . $dev_id;

            $nyd_data_select = "call  nyd_data_select(" . $param . "); ";
            $result = Db::query($nyd_data_select);
            // 结果集
            $result = $result[0][0]['last_res'];
            $result = explode(',', $result);

            if (!isset($dddd[$way])) {
                $dddd[$way] = [];
                array_push($dddd[$way], $result);
            } else {
                array_push($dddd[$way], $result);
            }

            if (!in_array($gateway, $legend['data'])) {
                array_push($legend['data'], $gateway);
                array_push($legend['selected'], ["$gateway" => true]);
            }
            $txt =  $yesterday . "   " . $this->sensor[$value['sensor_name']] . '指数';
            array_push($text,$txt);
            
            array_push($time_line, $value['sensor_name']);

        }

        $wangguan = Db::name('nyd_gateway')->column('gateway_id');
        foreach ($wangguan as $key => $value) {
            foreach ($dddd[$value] as $kk => $vo) {
                $row = [];
                foreach ($vo as $k => $v) {
                    $item['name'] = $x_title[$k];
                    $item['value'] = $v;
                    array_push($row, $item);
                }
                $series = [
                    'title'=> $text[$k],
                    'series' => [
                        'data' => $row
                    ]
                ];
                array_push($opt, $series);
            }
        }

        // 图标参数
        $option = [
            'baseOption' => [
                'timeline' => [
                    'axisType' => 'category',
                    'autoPlay' => true,
                    'playInterval' => 2000,
                    'data' => $time_line
                ],
                'title' => [
                    'top' => 0,
                    'left' => '42%'
                ],
                'tooltip' => [
                    'trigger' => 'axis'
                ],
                'calculable' => true,
                'grid' => [
                    'top' => 80,
                    'bottom' => 100,
                    'left' => 80,
                    'right' => 80
                ],
                'xAxis' => [
                    'type' => 'category',
                    'axisLabel' => ['interval' => 0],
                    'data' => $x_title,
                    'splitLine' => ['show' => false]
                ],
                'yAxis' => [
                    'type' => 'value',
                    'name' => '数据'
                ],
                'series' => [
                    'name' => '数值',
                    'type' => 'line',
                    'cursor' => 'pointer',
                    'lineStyle' => ['width' => 3],
                    'itemStyle' => ['borderWidth' => 3],
                ]
            ],
            'options' => $opt
        ];
        $yes_day = date('Y-m-d', time() - 86400);
        Cache::store('redis')->set('nyd_data_' . $yes_day, json_encode($option));
        return $option;
    }

    /**
     * 假数据
     *
     * @return void
     */
    public function jiadata()
    {
        $x_title = ['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'];
        $time_line = $opt = [];


        $jiadadta =
            [
                [77, 1, 66, 41, 7, 5, 88, 36, 24, 15, 48, 96],
                [11, 18, 64, 35, 48, 62, 47, 59, 86, 23, 45, 75],
                [62, 3, 45, 17, 62, 3, 25, 48, 76, 99, 32, 1],
                [44, 26, 31, 38, 52, 61, 85, 47, 12, 6, 95, 8],
                [55, 23, 64, 75, 22, 9, 63, 47, 1, 25, 48, 63],
                [75, 42, 33, 82, 26, 34, 2, 16, 27, 34, 77, 63],
                [46, 82, 35, 69, 12, 3, 8, 5, 46, 92, 45, 88],
                [7, 26, 34, 58, 42, 69, 87, 45, 48, 95, 88, 24],
                [56, 84, 23, 56, 45, 42, 25, 36, 48, 75, 45, 55],
                [16, 54, 24, 36, 85, 15, 25, 42, 7, 9, 66, 52],
                [47, 23, 65, 11, 48, 62, 55, 33, 24, 12, 45, 62],
                [81, 2, 63, 57, 85, 94, 25, 66, 44, 72, 51, 96],
                [11, 77, 45, 86, 23, 32, 58, 5, 4, 24, 61, 94],
                [14, 25, 74, 58, 42, 63, 14, 85, 99, 42, 51, 77],
                [8, 44, 52, 63, 47, 85, 95, 64, 34, 61, 52, 88],
            ];
        $sensor = [
            '气压', '温度', '湿度', '二氧化碳', '光照', 'PM2.5', 'PM1', 'PM10',
            '风速', '风向', '噪音', '土湿度', '土温度', '电导', '养分'
        ];
        foreach ($jiadadta as $key => $result) {

            $row = [];
            foreach ($result as $k => $v) {
                $item['name'] = $x_title[$k];
                $item['value'] = $v;
                array_push($row, $item);
            }

            $yesterday = date('Y-m-d', (time() - 86400));
            $series = [
                'title' => [
                    'text' => $yesterday . "   " . $sensor[$key] . '指数'
                ],
                'series' => [
                    ['data' => $row],
                ]
            ];
            array_push($time_line, $sensor[$key]);
            array_push($opt, $series);
        }

        // 图标参数
        $option = [
            'baseOption' => [
                'timeline' => [
                    'axisType' => 'category',
                    'autoPlay' => true,
                    'playInterval' => 2000,
                    'data' => $time_line
                ],
                'title' => [
                    'top' => 0,
                    'left' => '42%'
                ],
                'tooltip' => [
                    'trigger' => 'axis',
                ],
                'calculable' => true,
                'grid' => [
                    'top' => 80,
                    'bottom' => 100,
                    'left' => 80,
                    'right' => 80
                ],
                'xAxis' => [
                    'type' => 'category',
                    'axisLabel' => ['interval' => 0],
                    'data' => $x_title,
                    'splitLine' => ['show' => false]
                ],
                'yAxis' => [
                    'type' => 'value',
                    'name' => '数据'
                ],
                
                'series' => [
                        'name' => '数值',
                        'type' => 'line',
                        'cursor' => 'pointer',
                        'lineStyle' => ['width' => 3],
                        'itemStyle' => ['borderWidth' => 3],
                    
                    
                ]
            ],
            'options' => $opt
        ];
        return $option;
    }

    // public function house()
    // {
    //     if (isset($_POST['value'])) {
    //         $data = $_POST;
    //         $sql = " update nyd_control_dev set is_open =" . $data['value'] . "   where id = " . $data['id'];
    //         $row = Db::name("nyd_control_dev")->execute($sql);
    //         if ($row) {
    //             $res['code'] = 1;
    //         } else {
    //             $res['code'] = 0;
    //         }
    //         return $res;
    //     } else {
    //         $sql = "SELECT a.id,b.gateway_id,a.gateway_id as wangguan_id,a.is_open,a.is_bad,a.control_shortname,a.control_id,a.open_imgUrl,a.close_imgUrl  from  nyd_control_dev  as a inner join  nyd_gateway as b on a.gateway_id = b.id and   a.is_del =1 and a.is_open =1 and a.gateway_id = 3";
    //         $result = Db::name("nyd_control_dev")->query($sql);
    //         $this->assign("result", $result);
    //         $this->assign("count", count($result));
    //         return $this->fetch();
    //     }
    // }
    // public function greenhouse()
    // {
    //     if (isset($_POST['value'])) {
    //         $data = $_POST;
    //         $sql = " update nyd_control_dev set is_open =" . $data['value'] . "   where id = " . $data['id'];
    //         $row = Db::name("nyd_control_dev")->execute($sql);
    //         if ($row) {
    //             $res['code'] = 1;
    //         } else {
    //             $res['code'] = 0;
    //         }
    //         return $res;
    //     } else {
    //         $sql = "SELECT a.id,b.gateway_id,a.gateway_id as wangguan_id,a.is_open,a.is_bad,a.control_shortname,a.control_id,a.open_imgUrl,a.close_imgUrl  from  nyd_control_dev  as a inner join  nyd_gateway as b on a.gateway_id = b.id and   a.is_del =1 and a.is_open =1 and a.gateway_id = 4 ";
    //         $result = Db::name("nyd_control_dev")->query($sql);
    //         $this->assign("result", $result);
    //         $this->assign("count", count($result));
    //         return $this->fetch();
    //     }
    // }
}
